<template>
  <dark-mode-container
    class="global-tab f-y-c w-full pl-16"
    :style="{ height: themeStore.tab.height + 'px' }"
  >
    <div ref="bsRef" flex-1-hidden h-full>
      <better-scroll
        ref="bsScrollRef"
        :options="{ scrollX: true, scrollY: false, click: false }"
      >
        <tab-detail @scroll="handleScroll" />
      </better-scroll>
    </div>
    <reload-button />
  </dark-mode-container>
</template>

<script setup lang="ts">
import { useElementBounding } from "@vueuse/core";
import { useTabStore, useThemeStore } from "@/store";
import { ReloadButton, TabDetail } from "./components";
import type { BScrollInstance } from "@better-scroll/core";

const route = useRoute();
const themeStore = useThemeStore();
const tabStore = useTabStore();

const bsRef = ref<HTMLElement>();
const { width: bsWidth, left: bsLeft } = useElementBounding(bsRef);

const bsScrollRef = ref<{ instance: BScrollInstance }>();

function handleScroll(clientX: number) {
  const currentX = clientX - bsLeft.value;
  const deltaX = currentX - bsWidth.value / 2;
  if (bsScrollRef.value) {
    const { maxScrollX, x: leftX } = bsScrollRef.value.instance;
    const rightX = maxScrollX - leftX;
    const update =
      deltaX > 0 ? Math.max(-deltaX, rightX) : Math.min(-deltaX, -leftX);
    bsScrollRef.value?.instance.scrollBy(update, 0, 300);
  }
}

function init() {
  tabStore.iniTabStore(route);
}

watch(
  () => route.fullPath,
  () => {
    tabStore.addTab(route);
    tabStore.setActiveTab(route.fullPath);
  }
);

// 初始化
init();
</script>

<style scoped>
.global-tab {
  box-shadow: 0 1px 2px rgb(0 21 41 / 8%);
}
</style>
